package com.practice.线程的几种状态示例;
/**
 * @program: tenghw-practice-demo
 * @author: tenghw
 * @create: 2024-08-08 13:20
 * @Version 1.0
 * @description: 线程的几种状态示例 - waiting等待状态
 **/
public class WaitingDemo {
    private static final Object lock = new Object();
    public static void main(String[] args) {

        Thread waitingThread = new Thread(() -> {
            synchronized (lock) {
                System.out.println("waitingThread: waiting on lock");
                try {
                    lock.wait(); // waitingThread释放锁，并进入waiting等待状态
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("waitingThread: interrupted中断");
                }
                System.out.println("waitingThread被唤醒后: 继续执行...");
            }
        });

        Thread notifyThread = new Thread(() -> {
            try {
                Thread.sleep(2000);// 让notifyThread稍后唤醒waitingThread
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("notifyThread: interrupted中断");
            }
            synchronized (lock) {
                System.out.println("notifyThread: 唤醒waitingThread");
                lock.notify(); // notifyThread唤醒waitingThread
                //lock.notifyAll(); // notifyThread唤醒所有等待的线程
            }
        });

        waitingThread.start();
        notifyThread.start();
    }
}